/* eslint-disable camelcase */
/* eslint-disable @typescript-eslint/explicit-function-return-type */
/* eslint-disable @typescript-eslint/no-explicit-any */
import { defineComponent, ref, Ref } from 'vue';
import {
  getEditorEmits,
  getEditorProps,
  useNamespace,
} from '@ibiz-template/vue3-util';
import dayjs from 'dayjs';
import { EditFormController, FormItemController } from '@ibiz-template/runtime';
import { CheckinFormCalendarController } from './checkin-form-calendar.controller';
import './checkin-form-calendar.scss';

export const CheckinFormCalendar = defineComponent({
  name: 'IBizCheckinFormCalendar',
  props: getEditorProps<CheckinFormCalendarController>(),
  emits: getEditorEmits(),
  setup(props) {
    const ns = useNamespace('checkin-form-calendar');

    // 选中时间-开始和结束时间
    const dateRange: Ref<string[]> = ref([]);
    // 范围选择器Ref
    const dateRangeRef: Ref<any> = ref();
    const workdays = [
      '星期一',
      '星期二',
      '星期三',
      '星期四',
      '星期五',
      '星期六',
      '星期日',
    ];
    // 开始日期
    const startDay = ref();
    // 结束日期
    const endDay = ref();

    // 所有周
    const weeks: Ref<Array<any>> = ref([]);

    // 第一次点击选中的开始时间
    const tempStartDay = ref();

    const c = props.controller as CheckinFormCalendarController;

    // 处理日历周分组
    const handleCalendarWeekGroup = () => {
      weeks.value = [];
      // 当前时间进度时间戳
      let temptime = new Date(startDay.value).getTime();
      const endtime = new Date(endDay.value).getTime();
      while (temptime <= endtime) {
        const tempweeks = new Array(7).fill('');
        // 当前星期几
        const day = new Date(temptime).getDay();
        const index = day === 0 ? 7 : day;
        for (let i = index; i < 8; i++) {
          const curData = temptime + (i - index) * 86400000;
          if (curData <= endtime) {
            tempweeks[i - 1] = dayjs(curData).format('YYYY-MM-DD');
          }
        }
        temptime += (8 - index) * 86400000;
        weeks.value.push(tempweeks);
      }
    };
    // 初始化日历,默认时间是当月1号到当前时间
    const form = (c.parent as FormItemController).form as EditFormController;
    const initCalendar = () => {
      const { n_checkin_date_gtandeq, n_checkin_date_ltandeq } = form.context;
      if (n_checkin_date_gtandeq && n_checkin_date_ltandeq) {
        dateRange.value = [n_checkin_date_gtandeq, n_checkin_date_ltandeq];
        startDay.value = n_checkin_date_gtandeq;
        endDay.value = n_checkin_date_ltandeq;
      } else {
        const current = new Date();
        const curMonth = current.getMonth() + 1;
        const curYear = current.getFullYear();
        startDay.value = dayjs(new Date(curYear, curMonth - 1, 1)).format(
          'YYYY-MM-DD',
        );
        endDay.value = dayjs(current).format('YYYY-MM-DD');
        dateRange.value = [startDay.value, endDay.value];
      }
      handleCalendarWeekGroup();
    };
    initCalendar();

    // 根据日期范围获取对应的事件数据
    const getEventData = (currentday: string) => {
      if (currentday) {
        const { attendance_data } = props.data;
        if (attendance_data) {
          return attendance_data[currentday];
        }
      }
      return '';
    };

    // 日期变化
    const onDaterangeChange = (...data: string[]) => {
      startDay.value = dayjs(data[0][0]).format('YYYY-MM-DD');
      endDay.value = dayjs(data[0][1]).format('YYYY-MM-DD');
      tempStartDay.value = null;
      console.log('数据', data);
      // 重新计算需要绘制的日期范围
      handleCalendarWeekGroup();
    };

    // 设置禁用项，大于当前时间或者小于最小时间时禁用
    const disabledDate = (date: Date) => {
      if (date.getTime() > new Date().getTime()) {
        return true;
      }
      if (tempStartDay.value) {
        if (tempStartDay.value.getTime() > date.getTime()) {
          return true;
        }
        if (tempStartDay.value.getTime() + 31 * 86400000 < date.getTime()) {
          return true;
        }
      }
      return false;
    };

    // 绘制日历
    const renderCalendar = () => {
      return weeks.value.map((week: any[]) => {
        return (
          <div class={ns.e('weekgroup')}>
            {week.map((item: string) => {
              const eventData = getEventData(item);
              let details: IData[] = [];
              if (eventData && eventData.details) {
                details = eventData.details;
              }
              return (
                <div class={ns.e('week')}>
                  <div class={ns.em('week', 'datetime')}>{item}</div>
                  <div class={ns.em('week', 'dataevent')}>
                    {details.map((detail: IData) => {
                      return (
                        <div
                          class={[
                            ns.em('week', 'event-item'),
                            ns.is(
                              'no-normal',
                              detail.checkin_result !== 'NORMAL',
                            ),
                          ]}
                        >
                          {detail.checkin_time || '-'}
                        </div>
                      );
                    })}
                  </div>
                </div>
              );
            })}
          </div>
        );
      });
    };

    // 日历点击变化
    const onCalendarChange = (val: [Date, null | Date]) => {
      if (!tempStartDay.value) {
        tempStartDay.value = val[0];
      }
    };

    return {
      ns,
      workdays,
      dateRange,
      dateRangeRef,
      disabledDate,
      renderCalendar,
      onDaterangeChange,
      onCalendarChange,
    };
  },
  render() {
    // 绘制时间范围选择器
    const renderDateRange = () => {
      return (
        <el-date-picker
          ref='dateRangeRef'
          v-model={this.dateRange}
          class={this.ns.em('header', 'date-range')}
          type='daterange'
          range-separator='⇀'
          disabled-date={this.disabledDate}
          start-placeholder='开始日期'
          end-placeholder='结束日期'
          onChange={this.onDaterangeChange}
          onCalendar-change={this.onCalendarChange}
        ></el-date-picker>
      );
    };
    return (
      <div class={this.ns.b()}>
        <div class={this.ns.e('header')}>{renderDateRange()}</div>
        <div class={this.ns.e('workdays')}>
          {this.workdays.map(item => {
            return <div class={this.ns.e('workday')}>{item}</div>;
          })}
        </div>
        <div class={this.ns.e('context')}>{this.renderCalendar()}</div>
      </div>
    );
  },
});
